package com.aqie.rabbit.bean.api.base;

import com.alibaba.fastjson.annotation.JSONField;
import com.google.gson.annotations.Expose;

import java.io.Serializable;
import java.time.LocalDateTime;

public class ResponseModel <M> implements Serializable {
    // 成功
    public static final int SUCCEED = 1;
    // 未知错误
    public static final int ERROR_UNKNOWN = 0;

    @Expose
    private int code;
    @Expose
    private String message;

    @JSONField(format="yyyy-MM-dd HH:mm:ss")
    @Expose
    private LocalDateTime time = LocalDateTime.now();

    @Expose
    private M result;


    public int getCode() {
        return code;
    }

    public boolean isSucceed() {
        return code == SUCCEED;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public LocalDateTime getTime() {
        return time;
    }

    public void setTime(LocalDateTime time) {
        this.time = time;
    }

    public M getResult() {
        return result;
    }

    public void setResult(M result) {
        this.result = result;
    }


    public ResponseModel() {
        code = 1;
        message = "ok";
    }

    public ResponseModel(M result) {
        this();
        this.result = result;
    }

    public ResponseModel(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public ResponseModel(int code, String message, M result) {
        this.code = code;
        this.message = message;
        this.result = result;
    }

    public static <M> ResponseModel<M> success() {
        return new ResponseModel<M>();
    }


    // 成功时调用
    public static <M> ResponseModel<M> success(M result) {
        return new ResponseModel<M>(result);
    }

    public static <M> ResponseModel<M> buildCreateError(int type) {
        return new ResponseModel<M>(type, "Create failed.");
    }

    // 失败时调用
    public static <M> ResponseModel<M> error(CodeMsg codeMsg){
        return new ResponseModel<M>(codeMsg);
    }

    private ResponseModel(CodeMsg codeMsg){
        if (codeMsg == null)
            return;
        this.code = codeMsg.getCode();
        this.message = codeMsg.getMsg();
    }

}
